package data

import (
	"context"
	"shop-demo/app/user/service/internal/biz"
	user_ent "shop-demo/app/user/service/internal/data/ent/user"
)

type userRepo struct {
	data *Data
}

func NewUserRepo(data *Data) biz.UserRepo {
	return &userRepo{
		data: data,
	}
}

func (u *userRepo) CreateUser(ctx context.Context, user *biz.User) (*biz.User, error) {
	newUser, err := u.data.db.User.Create().SetUsername(user.Username).SetPassword(user.Password).Save(ctx)
	if err != nil {
		return nil, err
	}
	return &biz.User{
		Id:       newUser.ID,
		Username: newUser.Username,
		Password: newUser.Password,
	}, nil
}

func (u *userRepo) VerifyPassword(ctx context.Context, user *biz.User) (*biz.User, error) {
	matchedUser, err := u.data.db.User.
		Query().
		Where(
			user_ent.Username(user.Username),
			user_ent.Password(user.Password)).
		Only(ctx)
	if err != nil {
		return nil, err
	}
	return &biz.User{
		Id:       matchedUser.ID,
		Username: matchedUser.Username,
	}, nil
}

func (u *userRepo) GetUser(ctx context.Context, id int64) (*biz.User, error) {
	matchedUser, err := u.data.db.User.
		Query().
		Where(user_ent.ID(id)).
		Only(ctx)
	if err != nil {
		return nil, err
	}
	return &biz.User{
		Id:       matchedUser.ID,
		Username: matchedUser.Username,
	}, nil
}
